package cn.cnic.user.component.system.service.Impl;


import cn.cnic.user.component.system.mapper.*;
import cn.cnic.user.component.system.model.*;
import cn.cnic.user.component.system.service.IPersonServices;
import cn.cnic.user.utils.*;
import cn.cnic.user.vo.PersonVo;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.beans.Transient;
import java.io.File;
import java.util.*;

@Service
@Transactional
public class PersonServicesImpl implements IPersonServices {

    Logger logger = LoggerUtil.getLogger();

    @Resource
    private PersonMapper personMapper;
    @Resource
    private AcademicTitleMapper academicTitleMapper;

    @Resource
    private CurrentPositionMapper currentPositionMapper;

    @Resource
    private CurrentTitleMapper currentTitleMapper;

    @Resource
    private ReviewExpertMapper reviewExpertMapper;

    @Resource
    private SocialTitleMapper socialTitleMapper;

    @Resource
    private WorkExperienceMapper workExperienceMapper;

    @Resource
    private DegreeMapper degreeMapper;

    @Resource
    private CurrentOrganizationMapper currentOrganizationMapper;

    @Resource
    private EducationMapper educationMapper;

    @Resource
    private OverSeaExperienceMapper overSeaExperienceMapper;

    @Resource
    private PostdoctorMapper postdoctorMapper;

    @Resource
    private AwardMapper awardMapper;

    @Resource
    private HonorMapper honorMapper;

    @Resource
    private AcademicianMapper academicianMapper;

    @Resource
    private OutstandingMapper outstandingMapper;

    @Resource
    private LeaderMapper leaderMapper;




    @Override
    @Transient
    public String savePersonVo(HttpServletRequest request, PersonVo personVo,MultipartFile avatar){
        //记录关联插入记录
        int counts = 0;
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        rtnMap.put("code", 500);
        rtnMap.put("errMsg", "采集失败失败,请稍后再试！");

        if (avatar.isEmpty()) {
            rtnMap.put("errMsg", "头像为空");
            return JsonUtils.toJsonNoException(rtnMap);
        }else{
            String upload =  FileUtils.upload(avatar,SysParamsCache.IMAGES_PATH);

            Map<String, Object> map = JSON.parseObject(upload);

            String code = (String) map.get("code");
            if ("500".equals(code)) {
                rtnMap.put("errMsg", "头像上传失败,请联系管理员！");
                return JsonUtils.toJsonNoException(rtnMap);
            }
            String path = (String) map.get("url");
            if(null != personVo){
            Person person = new Person();
            String id = SqlUtils.getUUID32();
            //取出关联表数据
            List<AcademicTitle> academicTitle = personVo.getAcademicTitle();//学术任职
            List<CurrentPosition> currentPosition = personVo.getCurrentPosition();//现任职务
            List<CurrentTitle> currentTitle = personVo.getCurrentTitle();//现任职称
            List<Degree> degree = personVo.getDegree();//最高学位
            List<ReviewExpert> reviewExpert = personVo.getReviewExpert();//评审专家
            List<SocialTitle> socialTitle = personVo.getSocialTitle();//社会任职
            List<WorkExperience> workExperience = personVo.getWorkExperience();//主要工作经历
            List<CurrentOrganization> currentOrganization = personVo.getCurrentOrganization();//现工作单位
            List<Education> education = personVo.getEducation();// 学历
            List<OverSeaExperience> overSeaExperience = personVo.getOverSeaExperience();// 海外交流/学习/研究经历
            List<Postdoctor> postdoctor = personVo.getPostdoctor();// 博士后经历
            List<Award> award = personVo.getAward();// 获奖情况
            List<Honor> honor = personVo.getHonor();// 荣誉
            List<Academician> academician = personVo.getAcademician();// 院士
            List<Outstanding> outstanding = personVo.getOutstanding();// 杰出人才
            List<Leader> leader = personVo.getLeader();// 首位/领军人物











            //  存放待执行的sql
              List<AcademicTitle> academicTitleList = new ArrayList<>();//学术任职
              List<CurrentPosition> currentPositionList = new ArrayList<>();//现任职务
              List<CurrentTitle> currentTitleList = new ArrayList<>();//现任职称
              List<Degree> degreeList = new ArrayList<>();//最高学位
              List<ReviewExpert> reviewExpertList = new ArrayList<>();//评审专家
              List<SocialTitle> socialTitleList = new ArrayList<>();//社会任职
              List<WorkExperience> workExperienceList = new ArrayList<>();//主要工作经历
              List<CurrentOrganization> currentOrganizationList = new ArrayList<>();//现工作单位
              List<Education> educationList = new ArrayList<>();// 学历
              List<OverSeaExperience> overSeaExperienceList = new ArrayList<>();// 海外交流/学习/研究经历
              List<Postdoctor> postdoctorList = new ArrayList<>();// 博士后经历
              List<Award> awardList = new ArrayList<>();// 获奖情况
              List<Honor> honorList = new ArrayList<>();// 荣誉
              List<Academician> academicianList = new ArrayList<>();// 院士
              List<Outstanding> outstandingList = new ArrayList<>();// 杰出人才

              List<Leader> leaderList = new ArrayList<>();// 首位/领军人物




            //省份处理一下
            String arr[] =  personVo.getProvince().split(",");
            personVo.setProvince(arr[1]);
            BeanUtils.copyProperties(personVo, person);
            person.setAvatar(path);//保存头像的路径
            person.setCreaterTime(new Date());
            person.setUpdateTime(new Date());
            person.setPersonid(id);
            int personNum = personMapper.insert(person);
            if (personNum >0){

                //person插入成功
                // 开始处理关联表

                //1.学术任职
                if(!CollectionUtils.isEmpty(academicTitle) && !academicTitle.isEmpty()){
                    for (AcademicTitle academicTitleInfo:academicTitle) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(academicTitleInfo.getTitle(),academicTitleInfo.getType(),academicTitleInfo.getOrganizationName())){
                            academicTitleInfo.setPersonId(id);
                            academicTitleInfo.setId(SqlUtils.getUUID32());
                            academicTitleInfo.setCreaterTime(new Date());
                            academicTitleInfo.setUpdateTime(new Date());
                            academicTitleList.add(academicTitleInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(academicTitleList) && !academicTitleList.isEmpty()){
                        //批量插入
                       int academicTitleListNnm = academicTitleMapper.insertList(academicTitleList);
                       counts += academicTitleListNnm;
                    }
                }

                //现任职务
                if(!CollectionUtils.isEmpty(currentPosition) && !currentPosition.isEmpty()){
                    for (CurrentPosition currentPositionInfo:currentPosition) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(currentPositionInfo.getPositionTitle(),currentPositionInfo.getDepartment(),currentPositionInfo.getOrganizationName())){
                            currentPositionInfo.setCreaterTime(new Date());
                            currentPositionInfo.setUpdateTime(new Date());
                            currentPositionInfo.setId(SqlUtils.getUUID32());
                            currentPositionInfo.setPersonId(id);
                            currentPositionList.add(currentPositionInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(currentPositionList) && !currentPositionList.isEmpty()){
                        //批量插入
                       int currentPositionListNum = currentPositionMapper.insertList(currentPositionList);
                        counts += currentPositionListNum;
                    }
                }
                //现任职称
                if(!CollectionUtils.isEmpty(currentTitle) && !currentTitle.isEmpty()){
                    for (CurrentTitle currentTitleInfo:currentTitle) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(currentTitleInfo.getPositionTitle(),currentTitleInfo.getDepartment(),currentTitleInfo.getOrganizationName())){
                            currentTitleInfo.setId(SqlUtils.getUUID32());
                            currentTitleInfo.setUpdateTime(new Date());
                            currentTitleInfo.setPersonId(id);
                            currentTitleInfo.setCreaterTime(new Date());
                            currentTitleList.add(currentTitleInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(currentTitleList) && !currentTitleList.isEmpty()){
                        //批量插入
                       int currentTitleListNum = currentTitleMapper.insertList(currentTitleList);
                        counts += currentTitleListNum;
                    }
                }
                //最高学位
                if(!CollectionUtils.isEmpty(degree) && !degree.isEmpty()){
                    for (Degree degreeInfo:degree) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(degreeInfo.getDegreeName(),degreeInfo.getCountryName(),degreeInfo.getMajor())){
                            degreeInfo.setPersonId(id);
                            degreeInfo.setCreaterTime(new Date());
                            degreeInfo.setId(SqlUtils.getUUID32());
                            degreeInfo.setUpdateTime(new Date());
                            degreeList.add(degreeInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(degreeList) && !degreeList.isEmpty()){
                        //批量插入
                      int degreeListNum = degreeMapper.insertList(degreeList);
                        counts += degreeListNum;
                    }
                }
                //评审专家
                if(!CollectionUtils.isEmpty(reviewExpert) && !reviewExpert.isEmpty()){
                    for (ReviewExpert reviewExpertInfo:reviewExpert) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(reviewExpertInfo.getProjectCategory(),reviewExpertInfo.getProjectConferOrgization(),reviewExpertInfo.getArea(),reviewExpertInfo.getProjectTitle())){
                            reviewExpertInfo.setId(SqlUtils.getUUID32());
                            reviewExpertInfo.setCreaterTime(new Date());
                            reviewExpertInfo.setPersonId(id);
                            reviewExpertInfo.setUpdateTime(new Date());
                            reviewExpertList.add(reviewExpertInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(reviewExpertList) && !reviewExpertList.isEmpty()){
                        //批量插入
                        int reviewExpertListNum = reviewExpertMapper.insertList(reviewExpertList);
                        counts += reviewExpertListNum;
                    }
                }
                //社会任职
                if(!CollectionUtils.isEmpty(socialTitle) && !socialTitle.isEmpty()){
                    for (SocialTitle socialTitleInfo:socialTitle) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(socialTitleInfo.getOrganizationName(),socialTitleInfo.getTitle())){
                            socialTitleInfo.setId(SqlUtils.getUUID32());
                            socialTitleInfo.setCreaterTime(new Date());
                            socialTitleInfo.setUpdateTime(new Date());
                            socialTitleInfo.setPersonId(id);
                            socialTitleList.add(socialTitleInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(socialTitleList) && !socialTitleList.isEmpty()){
                        //批量插入
                        int socialTitleListNum = socialTitleMapper.insertList(socialTitleList);
                        counts += socialTitleListNum;

                    }
                }
                //主要工作经历
                if(!CollectionUtils.isEmpty(workExperience) && !workExperience.isEmpty()){
                    for (WorkExperience workExperienceInfo:workExperience) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(workExperienceInfo.getOrganizationName(),workExperienceInfo.getTitle(),workExperienceInfo.getDepartment())){
                            workExperienceInfo.setPersonId(id);
                            workExperienceInfo.setCreaterTime(new Date());
                            workExperienceInfo.setUpdateTime(new Date());
                            workExperienceInfo.setId(SqlUtils.getUUID32());
                            workExperienceList.add(workExperienceInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(workExperienceList) && !workExperienceList.isEmpty()){
                        //批量插入
                       int workExperienceListNum = workExperienceMapper.insertList(workExperienceList);
                        counts += workExperienceListNum;
                    }
                }
                //现工作单位
                if(!CollectionUtils.isEmpty(currentOrganization) && !currentOrganization.isEmpty()){
                    for (CurrentOrganization currentOrganizationInfo:currentOrganization) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(currentOrganizationInfo.getOrganizationName(),currentOrganizationInfo.getDepartment())){
                            currentOrganizationInfo.setCreaterTime(new Date());
                            currentOrganizationInfo.setId(SqlUtils.getUUID32());
                            currentOrganizationInfo.setUpdateTime(new Date());
                            currentOrganizationInfo.setPersonId(id);
                            currentOrganizationList.add(currentOrganizationInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(currentOrganizationList) && !currentOrganizationList.isEmpty()){
                        //批量插入
                        int currentOrganizationListNum = currentOrganizationMapper.insertList(currentOrganizationList);
                        counts += currentOrganizationListNum;
                    }
                }

                //学历
                if(!CollectionUtils.isEmpty(education) && !education.isEmpty()){
                    for (Education educationInfo:education) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(educationInfo.getMajor(),educationInfo.getAcademicDegree(),educationInfo.getAcademicDegreeYear())){
                            educationInfo.setCreaterTime(new Date());
                            educationInfo.setUpdateTime(new Date());
                            educationInfo.setPersonId(id);
                            educationInfo.setId(SqlUtils.getUUID32());
                            educationList.add(educationInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(educationList) && !educationList.isEmpty()){
                        //批量插入
                        int educationListNum = educationMapper.insertList(educationList);
                        counts += educationListNum;
                    }
                }

                //海外交流/学习/研究经历
                if(!CollectionUtils.isEmpty(overSeaExperience) && !overSeaExperience.isEmpty()){
                    for (OverSeaExperience overSeaExperienceInfo:overSeaExperience) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(overSeaExperienceInfo.getMajor(),overSeaExperienceInfo.getTitle(),overSeaExperienceInfo.getCountryName())){
                            overSeaExperienceInfo.setId(SqlUtils.getUUID32());
                            overSeaExperienceInfo.setPersonId(id);
                            overSeaExperienceInfo.setCreaterTime(new Date());
                            overSeaExperienceInfo.setUpdateTime(new Date());
                            overSeaExperienceList.add(overSeaExperienceInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(overSeaExperienceList) && !overSeaExperienceList.isEmpty()){
                        //批量插入
                        int overSeaExperienceListNum = overSeaExperienceMapper.insertList(overSeaExperienceList);
                        counts += overSeaExperienceListNum;
                    }
                }

                //博士后经历
                if(!CollectionUtils.isEmpty(postdoctor) && !postdoctor.isEmpty()){
                    for (Postdoctor postdoctorInfo:postdoctor) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(postdoctorInfo.getMajor(),postdoctorInfo.getAdvisor(),postdoctorInfo.getCountryName())){
                            postdoctorInfo.setId(SqlUtils.getUUID32());
                            postdoctorInfo.setPersonId(id);
                            postdoctorInfo.setCreaterTime(new Date());
                            postdoctorInfo.setUpdateTime(new Date());
                            postdoctorList.add(postdoctorInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(postdoctorList) && !postdoctorList.isEmpty()){
                        //批量插入
                        int postdoctorListNum = postdoctorMapper.insertList(postdoctorList);
                        counts += postdoctorListNum;
                    }
                }

                //获奖情况
                if(!CollectionUtils.isEmpty(award) && !award.isEmpty()){
                    for (Award awardInfo:award) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(awardInfo.getAwardName(),awardInfo.getContent())){
                            awardInfo.setId(SqlUtils.getUUID32());
                            awardInfo.setPersonId(id);
                            awardInfo.setCreaterTime(new Date());
                            awardInfo.setUpdateTime(new Date());
                            awardList.add(awardInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(awardList) && !awardList.isEmpty()){
                        //批量插入
                        int awardListNum = awardMapper.insertList(awardList);
                        counts += awardListNum;
                    }
                }

                //荣誉
                if(!CollectionUtils.isEmpty(honor) && !honor.isEmpty()){
                    for (Honor honorInfo:honor) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(honorInfo.getTitle())){
                            honorInfo.setId(SqlUtils.getUUID32());
                            honorInfo.setPersonId(id);
                            honorInfo.setCreaterTime(new Date());
                            honorInfo.setUpdateTime(new Date());
                            honorList.add(honorInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(honorList) && !honorList.isEmpty()){
                        //批量插入
                        int honorListNum = honorMapper.insertList(honorList);
                        counts += honorListNum;
                    }
                }

                //院士
                if(!CollectionUtils.isEmpty(academician) && !academician.isEmpty()){
                    for (Academician academicianInfo:academician) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(academicianInfo.getName(),academicianInfo.getCountryName())){
                            academicianInfo.setId(SqlUtils.getUUID32());
                            academicianInfo.setPersonId(id);
                            academicianInfo.setCreaterTime(new Date());
                            academicianInfo.setUpdateTime(new Date());
                            academicianList.add(academicianInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(academicianList) && !academicianList.isEmpty()){
                        //批量插入
                        int academicianListNum = academicianMapper.insertList(academicianList);
                        counts += academicianListNum;
                    }
                }

                //杰出人才
                if(!CollectionUtils.isEmpty(outstanding) && !outstanding.isEmpty()){
                    for (Outstanding outstandingInfo:outstanding) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(outstandingInfo.getTitle())){
                            outstandingInfo.setId(SqlUtils.getUUID32());
                            outstandingInfo.setPersonId(id);
                            outstandingInfo.setCreaterTime(new Date());
                            outstandingInfo.setUpdateTime(new Date());
                            outstandingList.add(outstandingInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(outstandingList) && !outstandingList.isEmpty()){
                        //批量插入
                        int outstandingListNum = outstandingMapper.insertList(outstandingList);
                        counts += outstandingListNum;
                    }
                }


                //首位/领军人物
                if(!CollectionUtils.isEmpty(leader) && !leader.isEmpty()){
                    for (Leader leaderInfo:leader) {
                        //判断关键参数是否为null,如果不为null则保存,否则跳过不保存;
                        if (!StringUtils.isAllBlank(leaderInfo.getTitle(),leaderInfo.getDescription())){
                            leaderInfo.setId(SqlUtils.getUUID32());
                            leaderInfo.setPersonId(id);
                            leaderInfo.setCreaterTime(new Date());
                            leaderInfo.setUpdateTime(new Date());
                            leaderList.add(leaderInfo);
                        }else{
                            continue;
                        }
                    }
                    if (!CollectionUtils.isEmpty(leaderList) && !leaderList.isEmpty()){
                        //批量插入
                        int leaderListNum = leaderMapper.insertList(leaderList);
                        counts += leaderListNum;
                    }
                }



                logger.info("关联表插入记录数："+counts);
                //大于0表示关联表有插入成功
                if(counts > 0){
                    rtnMap.put("code", 200);
                    rtnMap.put("errMsg", "您的信息已采集成功！");
                    logger.info("人员信息已采集成功,时间:"+ DateUtils.dateTimeToStr(new Date()));
                }
            }else{
                rtnMap.put("errMsg", "person插入失败");
                logger.info("person插入失败");
            }
        }else{
            rtnMap.put("errMsg", "数据为null,请检查后在提交");
            logger.info("后台接收数据为null,请检查后在提交");
        }
        return JsonUtils.toJsonNoException(rtnMap);
    }
    }

}

